<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import {
  createKnoDocGroup,
  getKnoDocGroupList,
  KnoDocGroup
} from "../../../api/knoDocGroup";
import KDGCreate from "./KDGCreate.vue";

const props = defineProps<{
  current?: KnoDocGroup;
}>();

const emit = defineEmits(["change"]);

const current = ref(props.current);

// 命名空间列表
const docGroupList = ref([]);
const kdgCreateForm = ref();
const loading = ref(false);
const noMore = ref(false);

const disabled = computed(() => loading.value || noMore.value);

// 查询参数
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  title: ""
});

const loadMore = async () => {
  if (loading.value || noMore.value) {
    return;
  }
  loading.value = true;
  const { ok, data } = await getKnoDocGroupList(query);
  if (ok) {
    docGroupList.value.push(...data.list);
  }
  if (data.list.length < query.pageSize) {
    noMore.value = true;
  }
  loading.value = false;
  query.pageNum++;
};

const reload = () => {
  query.pageNum = 1;
  loading.value = false;
  noMore.value = false;
  docGroupList.value = [];
  loadMore().then(() => {
    if (docGroupList.value.length > 0) {
      onClick(docGroupList.value[0]);
    }
  });
};

const showCreate = () => {
  kdgCreateForm.value?.open();
};

const submit = async (data: KnoDocGroup) => {
  const { ok, msg } = await createKnoDocGroup(data);
  if (ok) {
    reload();
  }
};

const onClick = (item: KnoDocGroup) => {
  emit("change", item);
  current.value = item;
};

onMounted(() => {
  reload();
});

defineExpose({
  showCreate
});
</script>

<template>
  <div>
    <KDGCreate ref="kdgCreateForm" @submit="submit" />
    <ul v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled">
      <li
        v-for="item in docGroupList"
        :key="item.id"
        :class="['ns-item', current?.id === item.id ? 'ns-active' : '']"
        @click="onClick(item)"
      >
        <el-text>{{ item.title }}</el-text>
        <el-dropdown class="ns-opt">
          <el-icon>
            <More />
          </el-icon>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>修改</el-dropdown-item>
              <el-dropdown-item>删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </li>
      <div v-if="loading" v-loading="true" />
    </ul>
  </div>
</template>
<style lang="scss" scoped>
.ns-item {
  display: flex;
  margin: 2px 5px;
  border-radius: 4px;
  overflow: hidden;
  padding: 0 5px;
  align-items: center;
  height: 50px;
  background-color: var(--el-menu-bg-color);
  cursor: pointer;
  flex-direction: row;
  justify-content: space-between;
  transition: all 0.3s ease-in-out;

  .ns-opt {
    display: none;
  }

  &:hover {
    background-color: var(--el-menu-hover-bg-color);
    .ns-opt {
      display: block;
    }
  }
}

.ns-active {
  background-color: #f5f7fa;
}
</style>
